//
//  DownloadView.swift
//  YoruNeko
//
//  Created by liphone on 2021/6/10.
//

import SwiftUI


final class ConstLabelName{
    static let download="下载"
    static let back="返回"
    static let searchBarPlaceholder="检索条目"
}


let SYSTEM_IMAGE_NAME=[
    "lessthan","plus"
]



struct DownloadView: View {
    
    
    
    
    //var data: [DownloadViewDataModel];
    @EnvironmentObject var dataModel:DownloadViewModelData
    
    private var filterItems:[DownloadViewItem]{
        dataModel.data.filter{ viewItem in
            searchKeyword.isEmpty || viewItem.title.contains(searchKeyword) || YRNKUtil.isSubSequence(viewItem.title, sub_str: searchKeyword)
        }
    }
    
    var callback:DownloadViewCallBack?
    
    @State var searchKeyword:String="";
    @State private var isAlertPresented = false
    @State private var alertSenderIndex = -1
    @State private var alertText:String = ""
    
    @State private var newTaskUrlStr:String = ""
    @State private var newTaskFileName:String = ""
    @State private var isCreateNewTaskPresented = false
    
    var body: some View {
        
        
        VStack{
            HStack(alignment: .center){
                Button(action:onBackButtonPressed){
                    Label(
                        title: { Text(ConstLabelName.back) },
                        icon: { Image(systemName: SYSTEM_IMAGE_NAME[0]) }
                    )
                }
                Spacer()
                Text(ConstLabelName.download).font(.title3).bold().offset(x: -20, y: 0)
                Spacer()
                Button(action:onPlusButtonPressed){
                    Label(
                        title: { },
                        icon: { Image(systemName: SYSTEM_IMAGE_NAME[1]) }
                    )
                }.scaleEffect(x: 1.5, y: 1.5, anchor: .center)
                .popover(isPresented: $isCreateNewTaskPresented,arrowEdge: .bottom, content: {
                    CreateNewDownloadAlertView(urlStr: $newTaskUrlStr, fileName: $newTaskFileName)
                })
//                .sheet(isPresented: $isCreateNewTaskPresented, content: {
//                    CreateNewDownloadAlertView(
//                        urlStr: $newTaskUrlStr, fileName: $newTaskFileName)
//                })
                
            }.frame(height:35)
            .padding([.top, .leading, .trailing], 6.0)
            .padding(.bottom,-3)
            
            
            Divider().frame(height:5)
            //ScrollView(content: {
            
            ScrollView{
                VStack{
                    
//                    Button("add", action: {
//                        dataModel.data[0].downloadedSize += 60000
//                    })
                    
                    TextField(" 检索条目", text: $searchKeyword, onEditingChanged: onEditingSearchBarChanged, onCommit: onEditCommit)
                        .padding()
                        
                        
                        
                        
                        .frame( height: 30)
                        .disableAutocorrection(true)
                        .autocapitalization(.none)
                        
                        .background(Rectangle().foregroundColor(Color(hue: 1, saturation: 0.0, brightness: 0.833)).cornerRadius(8)
                                        .shadow(color: .gray, radius: 2, x: 0.0/*@END_MENU_TOKEN@*/, y: /*@START_MENU_TOKEN@*/0.0)
                                        .overlay(
                                            HStack{
                                                Image(systemName: "magnifyingglass")
                                                    .foregroundColor(.gray)
                                            }, alignment: .leading)
                                    
                        )
                    
                    
                    ForEach(filterItems, id: \.id){ item in
                        DownloadItemView(with: item,
                                         onStateControllBtnPress:onStateControllBtnPress,
                                         onTrashBtnPress: displayAlert,
                                         onItemPress: onItemPress)
                            
                            .transition(.opacity).animation(.default)
                    }
                    
                }.padding()
                
                
            }.padding(.top,-10)
            //})
            
            
        }.alert(isPresented: $isAlertPresented, content: {
            Alert(
                title:Text("警告"),
                message:Text(alertText) ,
                primaryButton: .default(
                    Text("不了"),
                    action: {
                        isAlertPresented = false
                    }
                ),
                secondaryButton: .destructive(
                    Text("删除"),
                    action: {
                        if alertSenderIndex != -1 {
                            deleteItemAt(index: alertSenderIndex)
                        }
                    }
                )
            )
            
        }).transition(.move(edge: .trailing)).animation(.default)
        
        
        
    }
    
    
    func onBackButtonPressed()->Void{
        callback?.goBack()
    }
    
    func onPlusButtonPressed()->Void{
        isCreateNewTaskPresented = true;
    }
    
    
    func onStateControllBtnPress(id:Int)->Void{
        
    }
    
    func displayAlert(id:Int)->Void{
        
        if let index = dataModel.data.firstIndex(where: { item in
            return item.id.hashValue == id
        }){
            isAlertPresented = true
            let item = dataModel.data[index]
            alertText = "是否删除\"\(item.title)\""
            alertSenderIndex = index
            //deleteItemAt(index: index)
        }
        else {
            alertSenderIndex = -1
        }
        
        
    }
    
    func deleteItemAt(index:Int){
        
        //safety delete
        if dataModel.data.indices.contains(index) {
            
            let id = dataModel.data[index].id.hashValue
            dataModel.data.remove(at: index)
            
            NSLog("[DownloadView:] delete item at %d", index )
            callback?.deleteDownloadItemById(id: id)
        }
      
    }
    
    
    
    func onItemPress(id:Int)->Void{
        NSLog("[DownloadView:] pressed item id = %d",id)
        callback?.openFile(item_id_hashValue: id)
    }
    
    //
    func onEditingSearchBarChanged(isEditing:Bool)->Void{
        
    }
    
    func onEditCommit(){
        
    }
    
    
}



struct DownloadView_Previews: PreviewProvider {
    static var previews: some View {
        DownloadView().environmentObject(
            DownloadViewModelData(with:
                                    [DownloadViewItem("picture", urlStr: "www.hgc.ink", contentLength: 4400000),
                                     DownloadViewItem("dog", urlStr: "www.hgc.ink", contentLength: 4400000),
                                     DownloadViewItem("cat", urlStr: "www.hgc.ink", contentLength: 4400000),
                                     DownloadViewItem("tiger", urlStr: "www.xuzicheng.ink", contentLength: 4400000)])
        )
    }
}
